<template>
  <admin-layout>
    <div class="reviews-view">
      <h2 class="page-title">评价管理</h2>

      <!-- 搜索区域 -->
      <el-card class="search-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="商品名称">
            <el-input
              v-model="searchForm.productName"
              placeholder="请输入商品名称"
              clearable
            />
          </el-form-item>

          <el-form-item label="商家名称">
            <el-input
              v-model="searchForm.storeName"
              placeholder="请输入商家名称"
              clearable
            />
          </el-form-item>

          <el-form-item label="用户名">
            <el-input
              v-model="searchForm.username"
              placeholder="请输入用户名"
              clearable
            />
          </el-form-item>

          <el-form-item label="评分">
            <el-select
              v-model="searchForm.rating"
              placeholder="请选择评分"
              clearable
            >
              <el-option
                v-for="item in ratingOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 评价列表 -->
      <el-card class="table-card" v-loading="loading">
        <el-table :data="reviewList" border style="width: 100%" row-key="id">
          <el-table-column prop="id" label="ID" width="80" />

          <!-- <el-table-column
            prop="productName"
            label="商品名称"
            min-width="120"
          /> -->

          <el-table-column prop="storeName" label="商家名称" min-width="120" />

          <el-table-column prop="username" label="用户名" min-width="100" >
            <template #default="{ row }">
              <span>{{ row.userName || "匿名用户" }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="rating" label="评分" width="160">
            <template #default="{ row }">
              <star-rating :score="row.storeRating" :precision="1" />
            </template>
          </el-table-column>

          <el-table-column prop="content" label="评价内容" min-width="200">
            <template #default="{ row }">
              <div class="review-content">
                {{ row.content }}
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="评价时间" min-width="160">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>

          <!-- <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag
                :type="
                  row.status === 'normal'
                    ? 'success'
                    : row.status === 'hidden'
                    ? 'info'
                    : 'danger'
                "
              >
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column> -->

          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                @click="viewReviewDetail(row)"
              >
                查看
              </el-button>
              <el-button
                v-if="row.status === 'normal'"
                size="small"
                type="warning"
                @click="handleReviewStatus(row, 'hidden')"
              >
                隐藏
              </el-button>
              <el-button
                v-if="row.status === 'hidden'"
                size="small"
                type="success"
                @click="handleReviewStatus(row, 'normal')"
              >
                显示
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleReviewStatus(row, 'deleted')"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <div v-if="reviewList.length === 0 && !loading" class="empty-data">
          暂无评价数据
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="pagination.total > 0">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            :page-size="pagination.pageSize"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          />
        </div>
      </el-card>

      <!-- 评价详情对话框 -->
      <el-dialog
        v-model="detailDialog.visible"
        title="评价详情"
        width="700px"
        class="review-detail-dialog"
      >
        <div class="review-detail" v-if="detailDialog.review">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="商品名称">
              {{ detailDialog.review.productName }}
            </el-descriptions-item>
            <el-descriptions-item label="商家名称">
              {{ detailDialog.review.storeName }}
            </el-descriptions-item>
            <el-descriptions-item label="用户名">
              {{ detailDialog.review.username }}
            </el-descriptions-item>
            <el-descriptions-item label="评分">
              <star-rating :score="detailDialog.review.rating" :precision="1" />
            </el-descriptions-item>
            <el-descriptions-item label="评价时间">
              {{ formatDate(detailDialog.review.createTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag
                :type="
                  detailDialog.review.status === 'normal'
                    ? 'success'
                    : detailDialog.review.status === 'hidden'
                    ? 'info'
                    : 'danger'
                "
              >
                {{ getStatusLabel(detailDialog.review.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="评价内容" :span="2">
              {{ detailDialog.review.content }}
            </el-descriptions-item>
          </el-descriptions>

          <!-- 评价图片 -->
          <div
            class="review-images"
            v-if="
              detailDialog.review.images &&
              detailDialog.review.images.length > 0
            "
          >
            <h3>评价图片</h3>
            <div class="image-list">
              <el-image
                v-for="(image, index) in detailDialog.review.images"
                :key="index"
                :src="image"
                :preview-src-list="detailDialog.review.images"
                fit="cover"
                class="review-image"
              />
            </div>
          </div>

          <!-- 商家回复 -->
          <div class="merchant-reply" v-if="detailDialog.review.merchantReply">
            <h3>商家回复</h3>
            <div class="reply-content">
              <p>{{ detailDialog.review.merchantReply }}</p>
              <span class="reply-time">
                {{ formatDate(detailDialog.review.replyTime) }}
              </span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="dialog-footer">
            <el-button
              v-if="detailDialog.review.status === 'normal'"
              type="warning"
              @click="
                handleReviewStatus(detailDialog.review, 'hidden', () => {
                  detailDialog.visible = false;
                })
              "
            >
              隐藏评价
            </el-button>
            <el-button
              v-if="detailDialog.review.status === 'hidden'"
              type="success"
              @click="
                handleReviewStatus(detailDialog.review, 'normal', () => {
                  detailDialog.visible = false;
                })
              "
            >
              显示评价
            </el-button>
            <el-button
              type="danger"
              @click="
                handleReviewStatus(detailDialog.review, 'deleted', () => {
                  detailDialog.visible = false;
                })
              "
            >
              删除评价
            </el-button>
            <el-button @click="detailDialog.visible = false">关闭</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </admin-layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import AdminLayout from "@/components/admin/AdminLayout.vue";
import { getReviews, deleteReview } from "@/api/index";
import StarRating from "@/components/common/StarRating.vue";

// 定义评价类型
interface Review {
  id: string;
  productName: string;
  storeName: string;
  username: string;
  rating: number;
  content: string;
  images?: string[];
  merchantReply?: string;
  replyTime?: string;
  createTime: string;
  status: string;
}

// 评价列表
const reviewList = ref<Review[]>([]);

// 加载状态
const loading = ref(false);

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 搜索参数
const searchForm = reactive({
  productName: "",
  storeName: "",
  username: "",
  rating: "",
  status: "",
});

// 评分选项
const ratingOptions = [
  { value: "5", label: "5星" },
  { value: "4", label: "4星" },
  { value: "3", label: "3星" },
  { value: "2", label: "2星" },
  { value: "1", label: "1星" },
];

// 状态选项
const statusOptions = [
  { value: "normal", label: "正常" },
  { value: "hidden", label: "已隐藏" },
  { value: "deleted", label: "已删除" },
];

// 详情对话框
const detailDialog = reactive({
  visible: false,
  review: null as Review | null,
});

// 获取评价列表
const fetchReviews = async () => {
  loading.value = true;
  try {
    const params: Record<string, any> = {
      page: pagination.currentPage,
      size: pagination.pageSize,
    };

    // 只添加有值的搜索条件
    if (searchForm.productName) params.productName = searchForm.productName;
    if (searchForm.storeName) params.storeName = searchForm.storeName;
    if (searchForm.username) params.username = searchForm.username;
    if (searchForm.rating) params.rating = searchForm.rating;
    if (searchForm.status) params.status = searchForm.status;

    console.log("正在请求评价数据，参数:", params);
    const res = await getReviews(params);
    console.log("getReviews API响应:", res);

    const data = res.data?.data || res.data;
    console.log("解析后的数据:", data);

    if (data) {
      // 使用API文档中定义的分页格式
      reviewList.value = data.content || [];
      pagination.total = data.totalElements || 0;
      console.log("成功获取评价数据:", reviewList.value);
    } else {
      console.warn("API返回数据为空或格式不正确");
      reviewList.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error("获取评价列表失败:", error);
    ElMessage.error("获取评价列表失败，请检查网络连接或API状态");
    reviewList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchReviews();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  pagination.currentPage = 1;
  fetchReviews();
};

// 处理页面变化
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchReviews();
};

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchReviews();
};

// 获取状态标签
const getStatusLabel = (status: string): string => {
  const statusMap: Record<string, string> = {
    normal: "正常",
    hidden: "已隐藏",
    deleted: "已删除",
  };
  return statusMap[status] || status;
};

// 查看评价详情
const viewReviewDetail = (review: Review) => {
  detailDialog.review = review;
  detailDialog.visible = true;
};

// 处理评价状态
const handleReviewStatus = async (
  review: Review,
  status: string,
  callback?: () => void
) => {
  const statusText =
    status === "normal" ? "显示" : status === "hidden" ? "隐藏" : "删除";

  try {
    await ElMessageBox.confirm(`确定要${statusText}该评价吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 这里应该调用API更新评价状态
    // await updateReviewStatus(review.id, status);

    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 更新本地数据
    const index = reviewList.value.findIndex((item) => item.id === review.id);
    if (index !== -1) {
      reviewList.value[index].status = status;
    }

    // 如果是在详情对话框中操作，也更新详情数据
    if (detailDialog.review && detailDialog.review.id === review.id) {
      detailDialog.review.status = status;
    }

    ElMessage.success(`${statusText}评价成功`);

    // 如果提供了回调函数，则执行
    if (callback) {
      callback();
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error(`${statusText}评价失败:`, error);
      ElMessage.error(`${statusText}评价失败，请重试`);
    }
  }
};

// 格式化时间
const formatDate = (dateString?: string): string => {
  if (!dateString) return "";
  return dateString;
};

onMounted(() => {
  fetchReviews();
});
</script>

<style scoped>
.reviews-view {
  width: 100%;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  min-height: 400px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.empty-data {
  text-align: center;
  padding: 30px 0;
  color: var(--text-secondary);
  font-size: 14px;
}

.review-content {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.review-images {
  margin-top: 20px;
}

.review-images h3 {
  margin-bottom: 10px;
  font-size: 16px;
  color: var(--text-primary);
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.review-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  object-fit: cover;
}

.merchant-reply {
  margin-top: 20px;
}

.merchant-reply h3 {
  margin-bottom: 10px;
  font-size: 16px;
  color: var(--text-primary);
}

.reply-content {
  background-color: var(--bg-paper);
  padding: 10px;
  border-radius: 4px;
  border-left: 4px solid var(--primary);
}

.reply-content p {
  margin: 0;
  color: var(--text-primary);
}

.reply-time {
  display: block;
  margin-top: 5px;
  font-size: 12px;
  color: var(--text-secondary);
  text-align: right;
}

.dialog-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
